package com.ruoyi.master.config.redis;

import lombok.Data;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

@Data
@Component
@ConfigurationProperties(prefix = "redisstream")
public class RedisStreamConfig {
    static final String WECHAT = "wechat-msg";
    private String stream;
    private String group;
    private String consumer;
    private String wechatgroup;
    private String wechatconsumer;

    @Bean
    public CommandLineRunner createStreams(StringRedisTemplate redisTemplate) {
        return args -> {
            initStream(redisTemplate, this.stream, this.wechatgroup);
        };
    }

    private void initStream(StringRedisTemplate redisTemplate, String stream, String group) {
        try {
            // 尝试创建消费者组（Stream不存在时会自动创建）
            redisTemplate.opsForStream().createGroup(stream, group);
        } catch (Exception e) {
            if (!e.getMessage().contains("BUSYGROUP")) {
                throw new RuntimeException("初始化Stream失败: " + stream, e);
            }
            // 组已存在时忽略错误
        }
    }
}

